package com.hzhjhh.view.manageView.menus.purchase.purchaseOrder;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.math.BigDecimal;
import java.util.Objects;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import com.hzhjhh.dto.MerchandiseDTO;
import com.hzhjhh.entity.Merchandise;
import com.hzhjhh.mapper.MerchandiseMapper;
import com.hzhjhh.util.DBUtils;
import com.hzhjhh.view.manageView.menus.purchase.PurchaseOrderDialog;

/**
 * 菜单栏初始化-采购-采购表弹出框-商品编号
 * 
 * @author 12083
 *
 */
public class MerchandiseCode {

	private static MerchandiseMapper merchandiseMapper;

	/**
	 * 标签
	 * 
	 * @return
	 */
	public static JLabel lbInit() {
		JLabel merchandiseCode = new JLabel();
		merchandiseCode.setText("商品编号");
		merchandiseCode.setBounds(37, 28, 75, 21);

		return merchandiseCode;
	}
	
	/**
	 * 输入框
	 */
	public static JTextField txfInit(PurchaseOrderDialog stockDialog) {
		JTextField merchandiseCode = new JTextField();
		merchandiseCode.setBounds(104, 28, 111, 21);
        merchandiseCode.addFocusListener(new FocusAdapter() {

			@Override
			public void focusLost(FocusEvent e) {
		        String number = stockDialog.getTxfMerchandiseCode().getText(); //得到商品编号
		        if (StringUtils.isBlank(number)) {
		            return;
		        }
		        MerchandiseDTO merchandiseDTO = new MerchandiseDTO();
		        merchandiseDTO.setMerchandiseTreatyCode(number);
		        Merchandise merchandise = merchandiseMapper.selectOneByDTO(merchandiseDTO);
		        if(Objects.isNull(merchandise)){
		            JOptionPane.showMessageDialog(stockDialog, "无此商品", "错误",
		                    JOptionPane.ERROR_MESSAGE);
		            return;
		        }
		        JTextField txfPricePerOne = stockDialog.getTxfPricePerOne();
		        stockDialog.getTxfMerchandiseName().setText(merchandise.getMerchandiseName());
		        BigDecimal pricePerOne = merchandise.getMerchandiseRetailPrice();
		        txfPricePerOne.setText(pricePerOne.toString());
		        try {
		        	BigDecimal purchaseNum = new BigDecimal(stockDialog.getTxfPurchaseNum().getText());
		        	BigDecimal amt = pricePerOne.multiply(purchaseNum);
		        	stockDialog.getTxfAmt().setText(amt.toString());
		        } catch (Exception ex) {
		        	JOptionPane.showMessageDialog(stockDialog, "数量框中输入的不是数字", "错误",
		        			JOptionPane.ERROR_MESSAGE);
		        }
			}
        	
		});
        
        // mapper初始化
        SqlSession sqlSession = DBUtils.getSqlSession(true);
		merchandiseMapper = sqlSession.getMapper(MerchandiseMapper.class);
		
		return merchandiseCode;
	}
}
